//
//  GoodsCategoryVC.m
//  NormalFramework
//
//  Created by beisheng03 on 2018/3/10.
//  Copyright © 2018年 beisheng. All rights reserved.


#import "GoodsCategoryVC.h"
#import "CategoryRightCell.h"
#import "CategoryLeftCell.h"
#import "GoodsCateModel.h"
#import "BaseTableController.h"
#import "GoodsCategorySubVC.h"
@interface GoodsCategoryVC ()<UIScrollViewDelegate>


@property (nonatomic, weak) UIScrollView *titleScrollView;
@property (nonatomic, weak) UIScrollView *contentScrollView;
/** 上一次按钮 */
@property (nonatomic, weak) UIButton *selectButton;

@property (nonatomic, strong) NSMutableArray *titleButtons;

/** 下划线 */
@property (nonatomic, weak) UIView *underline;

/** <#note#> */
@property (nonatomic, weak) UITableView *leftTableView;

/** <#note#> */
@property (nonatomic, weak) UIView *bgView;

/** v */
@property (nonatomic, strong) NSMutableArray<GoodsCateModel *> *leftModels;
@end


#define XMGColor(r , g ,b) [UIColor colorWithRed:(r)  green:(g)  blue:(b) alpha:1]
#define XMGScreenW [UIScreen mainScreen].bounds.size.width
#define XMGScreenH [UIScreen mainScreen].bounds.size.height


@implementation GoodsCategoryVC

- (UIView *)bgView{
    
    if (!_bgView) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(80, 0, KScreenW - 80, KScreenH)];
        _bgView = view;
        _bgView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_bgView];
    }
    
    
    
    return _bgView;
}



- (NSMutableArray *)titleButtons
{
    if (!_titleButtons) {
        _titleButtons = [NSMutableArray array];
    }
    return _titleButtons;
}



- (UITableView *)leftTableView{
    
    if (_leftTableView == nil) {
        
        UITableView *temp = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 80, KScreenH) style:UITableViewStylePlain];
        
        temp.delegate = self;
        temp.dataSource = self;
        
        temp.showsVerticalScrollIndicator = NO;
        temp.showsHorizontalScrollIndicator = NO;
        
//        temp.tableFooterView = [[UIView alloc]init];
        
        temp.estimatedRowHeight = 56;
        temp.rowHeight = 56;
        temp.estimatedSectionHeaderHeight = 0;
        temp.estimatedSectionFooterHeight = 0;
        _leftTableView = temp;
        
        [self.view addSubview:temp];
        
    }
    
    return _leftTableView;
    
    
}






- (void)viewDidLoad {
    [super viewDidLoad];
     self.navigationItem.title = @"分类";
     self.view.backgroundColor = [UIColor whiteColor];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    
    

    
    if (@available(iOS 11.0, *)) {
        
        
        self.leftTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;

    }
    
    
    self.leftTableView.contentInset = UIEdgeInsetsMake(IPhoneX ? 88 : 64, 0, IPhoneX ? 34 : 0, 0);

    self.leftTableView.tableFooterView = [[UIView alloc]init];
    
    self.leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.leftTableView registerNib:[UINib nibWithNibName:NSStringFromClass([CategoryLeftCell class]) bundle:nil] forCellReuseIdentifier:[CategoryLeftCell identifierStr]];
    
    
    
    
    
    [self loadLeftData];
    
    
    self.seletIndex = 0;
    
    // 2.搭建内容滚动视图
    [self setupContentScrollView];
    
    
    
    // 1.搭建标题滚动视图
    [self setupTitleScrollView];
    
    
    // 3.添加子控制器
    [self setupAllChildViewController];
    
    // 取消添加额外滚动区域
    // 在scrollView,忽然发现内容放下走,就是顶部额外滚动区域做
    //    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 5.监听滚动完成
    self.contentScrollView.delegate = self;
    
    
    [self setupAllTitle];
    
    // Do any additional setup after loading the view.
}


#pragma mark -添加子控制器
- (void)setupAllChildViewController
{
    
//    1- 2- 3- 4-总需从小到大 5-总需从大到小
    
    GoodsCategorySubVC *first = [[GoodsCategorySubVC alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:first selector:@selector(goodsCateoryDidChange:) name:@"goodsCateoryDidChange" object:nil];
    first.title = @"人气";
    [self addChildViewController:first];
    
    GoodsCategorySubVC *secend = [[GoodsCategorySubVC alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:secend selector:@selector(goodsCateoryDidChange:) name:@"goodsCateoryDidChange" object:nil];
    secend.title = @"最新";
    [self addChildViewController:secend];
    
    GoodsCategorySubVC *third = [[GoodsCategorySubVC alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:third selector:@selector(goodsCateoryDidChange:) name:@"goodsCateoryDidChange" object:nil];
    third.title = @"进度";
    [self addChildViewController:third];
    
    GoodsCategorySubVC *four = [[GoodsCategorySubVC alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:four selector:@selector(goodsCateoryDidChange:) name:@"goodsCateoryDidChange" object:nil];
    four.title = @"价值";
    [self addChildViewController:four];
    
}



#pragma mark - 搭建标题滚动视图
- (void)setupTitleScrollView
{
    // 创建UIScrollView
    //    UIScrollView *scrollView = [[UIScrollView alloc] init];
    //    scrollView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.9];
    //
    //    CGFloat y = IPhoneX ? 88 : 64;
    //    CGFloat h = XMGTitlesViewH;
    //    CGFloat w = XMGScreenW;
    //    scrollView.frame = CGRectMake(0, y, w, h);
    //    [self.view addSubview:scrollView];
    
    
    
    UIScrollView *navTitleView = [[UIScrollView alloc]initWithFrame:CGRectMake(80, IPhoneX ? 88 : 64, KScreenW - 80, 36)];

    
    _titleScrollView = navTitleView;
    
    _titleScrollView.backgroundColor = viewBgGrey;//[UIColor colorWithWhite:0 alpha:0.1]
    
    [self.view addSubview:navTitleView];
    
    
    [self.view addSubview:self.bgView];
    
    self.bgView.hidden = NO;
    
}


#pragma mark - 搭建内容滚动视图
- (void)setupContentScrollView
{
    // 创建UIScrollView
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    //    CGFloat y = CGRectGetMaxY(_titleScrollView.frame);
    //    CGFloat h = XMGScreenH - y;
    //    CGFloat w = XMGScreenW;
    //    scrollView.frame = CGRectMake(0, y, w, h);
    
    scrollView.frame = CGRectMake(80, IPhoneX ? 124 : 100, KScreenW - 80, KScreenH - (IPhoneX ? 124 : 100));
    scrollView.backgroundColor = [UIColor greenColor];
    [self.view addSubview:scrollView];
    _contentScrollView = scrollView;
    
}



#pragma mark -设置标题
- (void)setupAllTitle
{
    // 添加所有标题
    NSUInteger count = self.childViewControllers.count;
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat w = (KScreenW - 80) * 0.25;
    
    CGFloat h = self.titleScrollView.bounds.size.height;
    
    for (NSUInteger i = 0; i < count; i++) {
        x = i * w;
        UIViewController *vc = self.childViewControllers[i];
        BaseDisablelightBtn *btn = [BaseDisablelightBtn buttonWithType:UIButtonTypeCustom];
        btn.titleLabel.font = MYFONT(14);
        btn.tag = i;
        btn.frame = CGRectMake(x, y, w, h);
        [btn setTitle:vc.title forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchDown];
        [self.titleScrollView addSubview:btn];
        
        // 添加到标题按钮数组
        [self.titleButtons addObject:btn];
        
    }
    
    //
    //    UIView *sliderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 72, 36)];
    //    sliderView.backgroundColor = [UIColor whiteColor];
    //    sliderView.layer.cornerRadius = 5;
    //    sliderView.layer.masksToBounds = YES;
    //    [self.titleScrollView insertSubview:sliderView atIndex:0];
    
    
    // 设置标题滚动范围
    self.titleScrollView.contentSize = CGSizeMake(count * w, 0);
    self.titleScrollView.showsHorizontalScrollIndicator = NO;
    
    // 设置内容滚动范围
    self.contentScrollView.contentSize = CGSizeMake(count * (XMGScreenW - 80), 0);
    self.contentScrollView.pagingEnabled = YES;
    self.contentScrollView.bounces = NO;
    self.contentScrollView.showsHorizontalScrollIndicator = NO;
    /*
     问题:1.按钮文字为黑色 2.标题滚动视图可以滚动
     */
    [self titleClick:self.titleButtons[self.seletIndex]];
    
    
    // 下划线
    [self setupUnderline];
}






- (void)loadLeftData{
    
    
    MJWeakSelf;
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:GET_METHOD URLPath:@"index.php/Api/Dbindex/categorys" parameters:nil completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
            weakSelf.leftModels = [GoodsCateModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"category_list"]];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"goodsCateoryDidChange" object:weakSelf.leftModels.firstObject];

            
            [weakSelf.leftTableView reloadData];
            
            [weakSelf.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];

            self.bgView.hidden = YES;
        }
        
        

        
    }];
    
    
    
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (self.leftModels == nil) {
        return 0;
    }
 
        return 1;

    
    
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.leftModels == nil) {
        return 0;
    }

        return self.leftModels.count;

    
    
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
  
        CategoryLeftCell *left = [tableView dequeueReusableCellWithIdentifier:[CategoryLeftCell identifierStr]];
    
    
    left.model = self.leftModels[indexPath.row];
        
        return left;

    
    
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
        return 0;

}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    
    return [[UIView alloc]init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    UIView *header = [[UIView alloc]init];
    
    header.backgroundColor = [UIColor whiteColor];
    
    return header;
}




- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    if (self.leftTableView == tableView)
    {
  
        [self.leftTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]
                              atScrollPosition:UITableViewScrollPositionMiddle
                                      animated:YES];
    }
    
    GoodsCateModel *model = self.leftModels[indexPath.row];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"goodsCateoryDidChange" object:model];
      

}







/**
 *  下划线
 */
- (void)setupUnderline
{
    // 标题按钮
    BaseDisablelightBtn *firstTitleButton = self.titleScrollView.subviews[self.seletIndex];
    
    UIView *underline = [[UIView alloc] init];
    CGFloat underlineH = 2;
    underline.frame = CGRectMake(0,  self.titleScrollView.height - underlineH, 0, underlineH);
    underline.backgroundColor = themeColor;
    [self.titleScrollView insertSubview:underline atIndex:0];
    self.underline = underline;
    
    // 默认选中最前面的按钮
    // 切换按钮状态
    firstTitleButton.selected = YES;
    //    self.selectButton = firstTitleButton;
    
    // 处理下划线
    [firstTitleButton.titleLabel sizeToFit];
    //    self.underline.width = KScreenW/self.childViewControllers.count;
    self.underline.width = (KScreenW - 80) * 0.25;
    
    
    self.underline.centerX = firstTitleButton.centerX;
}

#pragma mark -点击标题就会调用
- (void)titleClick:(UIButton *)button
{
    NSInteger i = button.tag;
    
    // 1.选中按钮
    [self selectBtn:button];
    
    // 2.需要把对应子控制器的view添加上去
    [self setupOneViewControllerView:i];
    
    // 3.设置内容滚动视图偏移量
    // 计算偏移量
    CGFloat offsetX = i * (XMGScreenW - 80);
    self.contentScrollView.contentOffset = CGPointMake(offsetX, 0);
}

#pragma mark -选中按钮
- (void)selectBtn:(UIButton *)selectBtn
{
    // 设置按钮颜色
    [_selectButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [selectBtn setTitleColor:themeColor forState:UIControlStateNormal];
    
    // 让标题居中
    //    [self setupTitleButtonCenter:selectBtn];
    
    // 标题缩放
    _selectButton.transform = CGAffineTransformIdentity;
    selectBtn.transform = CGAffineTransformMakeScale(1.3, 1.3);
    
    _selectButton = selectBtn;
    
    
    [UIView animateWithDuration:0.25 animations:^{
        // 处理下划线
        //        self.underline.width = KScreenW/self.childViewControllers.count;
        self.underline.width = (KScreenW - 80) * 0.25;
        self.underline.centerX = selectBtn.centerX;
        
    } completion:^(BOOL finished) {
        // 2.需要把对应子控制器的view添加上去
        //        [self setupOneViewControllerView:selectBtn.tag];
    }];
}

// 让标题居中
- (void)setupTitleButtonCenter:(UIButton *)button
{
    // 修改偏移量
    CGFloat offsetX = button.center.x - XMGScreenW * 0.5;
    
    // 处理最小滚动偏移量
    if (offsetX < 0) {
        offsetX = 0;
    }
    
    // 处理最大滚动偏移量
    CGFloat maxOffsetX = self.titleScrollView.contentSize.width - XMGScreenW;
    if (offsetX > maxOffsetX) {
        offsetX = maxOffsetX;
    }
    [self.titleScrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}

// 添加一个子控制器的view
- (void)setupOneViewControllerView:(NSInteger)i
{
    CGFloat x = i * (XMGScreenW - 80);
    
    UIViewController *vc = self.childViewControllers[i];
    if (vc.view.superview) return;
    
    //    CGFloat navH = IPhoneX ? 88 : 64;
    vc.view.frame = CGRectMake(x, 0, XMGScreenW - 80, self.contentScrollView.bounds.size.height);
    [self.contentScrollView addSubview:vc.view];
    
}
#pragma mark -UIScrollViewDelegate
// 减速完成就会调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger i = scrollView.contentOffset.x / (XMGScreenW - 80);
    
    // 获取对应标题按钮
    UIButton *selButton = self.titleButtons[i];
    
    // 选中标题
    [self selectBtn:selButton];
    
    // 添加对应子控制器的view
    [self setupOneViewControllerView:i];
}

// 只要滚动 就会调用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (scrollView == self.leftTableView) {
        return;
    }
    // 让按钮形变
    NSInteger leftI = scrollView.contentOffset.x / (XMGScreenW - 80);
    
    NSInteger rightI = leftI + 1;
    
    // 1.获取需要形变的按钮
    
    // left
    // 获取左边按钮
    UIButton *leftButton = self.titleButtons[leftI];
    
    // right
    NSUInteger count = self.childViewControllers.count;
    UIButton *rigthButton;
    // 获取右边按钮
    if (rightI < count) {
        rigthButton = self.titleButtons[rightI];
    }
    
    // 计算右边按钮偏移量
    CGFloat rightScale = scrollView.contentOffset.x / (XMGScreenW - 80);
    
    // 只想要 0~1
    rightScale = rightScale - leftI;
    
    
    CGFloat leftScale = 1 - rightScale;
    
    
    CGFloat rightBtnCenterX = rigthButton.centerX;
    CGFloat leftBtnCenterX = leftButton.centerX;
    
    
    CGFloat subtract = fabs(rightBtnCenterX - leftBtnCenterX);
    
    CGFloat temp = leftButton.centerX + rightScale * subtract;
    
    self.underline.centerX = temp;
    
    // 形变按钮
    // scale 0 ~ 1 => 1 ~ 1.3
    leftButton.transform = CGAffineTransformMakeScale(leftScale * 0.3 + 1, leftScale * 0.3 + 1);
    rigthButton.transform = CGAffineTransformMakeScale(rightScale * 0.3 + 1, rightScale * 0.3 + 1);
    
    // 颜色渐变 黑色 -> 红色
    //  XMGColor(rightScale, 0, 0)
    //    XMGColor(leftScale, 0, 0)
    [rigthButton setTitleColor:colorWith(233* rightScale, 58 * rightScale, 68 * rightScale) forState:UIControlStateNormal];
    [leftButton setTitleColor:colorWith(233 * leftScale, 58 * leftScale, 68 * leftScale) forState:UIControlStateNormal];
    
    //    self.underline.backgroundColor = colorWith(255* rightScale, 255 * rightScale, 255 * rightScale);
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation
j// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
